# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

import mindspore.nn as nn
import mindspore.ops as ops
import mindspore.ops.operations._inner_ops as inner

class ChannelNorm(nn.Cell):

    def __init__(self, axis=1):
        super(ChannelNorm, self).__init__()
        self.axis = axis
        self.norm = nn.Norm(axis)

    def construct(self, input):
        output = self.norm(input)
        output = output.reshape(output.shape[0], 1, output.shape[1], output.shape[2])
        return output


class Correlation(nn.Cell):

    def __init__(self, pad_size=0, kernel_size=0, max_displacement=0, stride1=1, stride2=2):
        super(Correlation, self).__init__()
        self.pad_size = pad_size
        self.kernel_size = kernel_size
        self.max_displacement = max_displacement
        self.stride1 = stride1
        self.stride2 = stride2
        self.correlation = inner.Correlation(pad_size, kernel_size, max_displacement, stride1, stride2)

    def construct(self, input1, input2):
        output = self.correlation(input1, input2)
        return output


class Resample2d(nn.Cell):

    def __init__(self, kernel_size=1, bilinear=True):
        super(Resample2d, self).__init__()
        self.kernel_size = kernel_size
        self.bilinear = bilinear
        self.resample2d = inner.Resample2D(kernel_size, bilinear)

    def construct(self, input1, input2):
        output = self.resample2d(input1, input2)
        return output


class Upsample(nn.Cell):

    def __init__(self, scale_factor=4, mode='bilinear'):
        super(Upsample, self).__init__()
        self.scale_factor = scale_factor
        self.mode = mode

    def construct(self, input):
        shape = input.shape
        new_height = shape[2] * self.scale_factor
        new_width = shape[3] * self.scale_factor
        if (self.mode == 'nearest'):
            upsample_op = ops.ResizeNearestNeighbor((new_height, new_width))
        else:
            upsample_op = ops.ResizeBilinear((new_height, new_width))
        return upsample_op(input)


def conv(batchnorm, in_planes, out_planes, kernel_size=3, stride=1):
    if batchnorm:
        conv2d = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, pad_mode='pad',
                           padding=(kernel_size - 1) // 2, has_bias=False)
        batchNorm2d = nn.BatchNorm2d(out_planes)
        leakyReLU = nn.LeakyReLU(0.1)
        return nn.SequentialCell([conv2d, batchNorm2d, leakyReLU])
    else:
        conv2d = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, pad_mode='pad',
                           padding=(kernel_size - 1) // 2, has_bias=True)
        leakyReLU = nn.LeakyReLU(0.1)
        return nn.SequentialCell([conv2d, leakyReLU])


def i_conv(batchNorm, in_planes, out_planes, kernel_size=3, stride=1, bias=True):
    if batchNorm:
        conv2d = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, pad_mode='pad',
                           padding=(kernel_size - 1) // 2, has_bias=bias)
        batchNorm2d = nn.BatchNorm2d(out_planes)
        return nn.SequentialCell([conv2d, batchNorm2d])
    else:
        conv2d = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, pad_mode='pad',
                           padding=(kernel_size - 1) // 2, has_bias=bias)
        return nn.SequentialCell([conv2d])


def predict_flow(in_planes):
    return nn.Conv2d(in_planes, 2, kernel_size=3, stride=1, pad_mode='pad', padding=1, has_bias=True)


def deconv(in_planes, out_planes):
    convTranspose2d = nn.Conv2dTranspose(in_planes, out_planes, kernel_size=4, stride=2, pad_mode='pad', padding=1,
                                         has_bias=True)
    leakyReLU = nn.LeakyReLU(0.1)
    return nn.SequentialCell([convTranspose2d, leakyReLU])

'''
def init_deconv_bilinear(weight):
    f_shape = weight.shape
    heigh, width = f_shape[-2], f_shape[-1]
    f = np.ceil(width / 2.0)
    c = (2 * f - 1 - f % 2) / (2.0 * f)
    bilinear = np.zeros([heigh, width])
    for x in range(width):
        for y in range(heigh):
            value = (1 - abs(x / f - c)) * (1 - abs(y / f - c))
            bilinear[x, y] = value
    weight.fill(0.)
    for i in range(f_shape[0]):
        for j in range(f_shape[1]):
            weight[i, j, :, :] = nn.Tensor(bilinear)
'''
